package main

import (
	"buaashow-gateway/config"
	"fmt"
	"log"
	"net/http"
	"net/http/httputil"
	"regexp"

	"github.com/gin-contrib/multitemplate"
	"github.com/gin-gonic/gin"
)

var cfg config.Config

func handleProxy(src, dst string) gin.HandlerFunc {
	target := cfg.ServeURL
	r, err := regexp.Compile(src)
	if err != nil {
		log.Fatal("正则表达式错误")
	}
	director := func(req *http.Request) {
		req.URL.Scheme = "http"
		req.URL.Host = target
		req.URL.Path = r.ReplaceAllString(req.URL.Path, dst)
	}
	return func(c *gin.Context) {
		proxy := &httputil.ReverseProxy{Director: director}
		proxy.ServeHTTP(c.Writer, c.Request)
	}
}

func createMyRender() multitemplate.Renderer {
	p := multitemplate.NewRenderer()
	fmt.Println(cfg.AdminPath)
	p.AddFromFiles("admin", fmt.Sprintf("%s/index.html", cfg.AdminPath))
	p.AddFromFiles("front", fmt.Sprintf("%s/index.html", cfg.FrontPath))
	return p
}

func Router() *gin.Engine {
	r := gin.Default()
	r.HTMLRender = createMyRender()

	r.Static("front", cfg.FrontPath)
	r.Static("admin", cfg.AdminPath)

	r.GET("/", func(c *gin.Context) {
		c.HTML(http.StatusOK, "front", nil)
	})
	r.GET("admin", func(c *gin.Context) {
		c.HTML(http.StatusOK, "admin", nil)
	})
	r.Any("api/*dst", handleProxy("api/", ""))

	return r
}

func main() {
	config.InitCfg(&cfg)
	log.Print(cfg)

	r := Router()

	r.Run(cfg.Port)
}
